package handler

import (
	"chat-box/global"
	"chat-box/pkg"
	"encoding/json"
	"fmt"
	"log"
	"strconv"

	"github.com/gin-gonic/gin"
)
import "github.com/gorilla/websocket"

type ChatHandler struct {
}

func NweChatHandler() *ChatHandler {
	return &ChatHandler{}
}

var upgrader = websocket.Upgrader{
	ReadBufferSize:  1024,
	WriteBufferSize: 1024,
}

func (ch ChatHandler) ChatIm(c *gin.Context) {
	u := c.Query("user_id")
	uid, _ := strconv.Atoi(u)
	conn, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		return
	}
	node := global.Node{
		Conn: conn,
		Data: make(chan []byte, 50),
	}
	global.ClientMge[uid] = node
	go ReadMessage(node)
	go WriteMessage(node)
}

func ReadMessage(node global.Node) {
	for {
		_, message, err := node.Conn.ReadMessage()
		if err != nil {
			return
		}
		var msg global.Message
		json.Unmarshal(message, &msg)
		if n, ok := global.ClientMge[msg.DienId]; ok {
			n.Data <- message
		}
	}
}

func WriteMessage(node global.Node) {
	for {
		data := <-node.Data
		node.Conn.WriteMessage(websocket.TextMessage, data)
	}
}
func (ch ChatHandler) Rabbits(c *gin.Context) {
	rabbitmq := pkg.NewRabbitMQSimple("" +
		"kuteng")
	simple := rabbitmq.PublishSimple("Hello kuteng222!")
	if simple == false {
		fmt.Println("发送失败")
	}
	fmt.Println("发送成功！")
}
func (ch ChatHandler) GetRabbits(c *gin.Context) {
	rabbitmq := pkg.NewRabbitMQSimple("" +
		"kuteng")
	msgs := rabbitmq.ConsumeSimple()
	forever := make(chan bool)
	//启用协程处理消息
	go func() {
		for d := range msgs {
			//消息逻辑处理，可以自行设计逻辑
			log.Printf("Received a message: %s", d.Body)

		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")
	<-forever
}
